//
//  RegisterViewController.m
//  SITABLE
//
//  Created by songjun on 16/9/27.
//  Copyright © 2016年 Sita. All rights reserved.
//

#import "RegisterViewController.h"

@interface RegisterViewController ()

@end

@implementation RegisterViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    

    self.title = NSLocalizedStringFromTable(@"NewUserRegister", @"InfoPlist", nil);

    //增加监听，当键盘出现或改变时收出消息
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(keyboardWillShow:)
                                                 name:UIKeyboardWillShowNotification
                                               object:nil];
    
    //增加监听，当键退出时收出消息
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(keyboardWillHide:)
                                                 name:UIKeyboardWillHideNotification
                                               object:nil];
    
    UITapGestureRecognizer *tapGes = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapGesAction:)];
    
    [self.view addGestureRecognizer:tapGes];
    // Do any additional setup after loading the view.
    avtarTf.returnKeyType = UIReturnKeyDone;
    passWordTf.returnKeyType =UIReturnKeyDone;
    phoneNuberTf.returnKeyType = UIReturnKeyDone;
    conformPassword.returnKeyType =UIReturnKeyDone;
    
    avtarTf.delegate = self;
    passWordTf.delegate =self;
    phoneNuberTf.delegate = self;
    conformPassword.delegate =self;

}

- (BOOL)textFieldShouldReturn:(UITextField *)textField
{
    [textField resignFirstResponder];
    //NSLog(@"点击了搜索");
    return YES;
}

//单击收回键盘
-(void)tapGesAction:(UITapGestureRecognizer *)ges
{
    [avtarTf resignFirstResponder];
    [passWordTf resignFirstResponder];
    [phoneNuberTf resignFirstResponder];
    [conformPassword resignFirstResponder];
}


//当键盘出现或改变时调用
- (void)keyboardWillShow:(NSNotification *)aNotification
{
    //获取键盘的高度
    NSDictionary *userInfo = [aNotification userInfo];
    float duaration = [[userInfo objectForKey:UIKeyboardAnimationDurationUserInfoKey] floatValue];
    NSValue *aValue = [userInfo objectForKey:UIKeyboardFrameEndUserInfoKey];
    CGRect keyboardRect = [aValue CGRectValue];
    int height = keyboardRect.size.height;
    [UIView animateWithDuration:duaration animations:^{
        self.view.frame = CGRectMake(0, -height/4, SCREEN_WIDTH, SCREEN_HEIGHT);
    }];
}

//当键退出时调用
- (void)keyboardWillHide:(NSNotification *)aNotification
{
    //获取键盘的高度
    NSDictionary *userInfo = [aNotification userInfo];
    float duaration = [[userInfo objectForKey:UIKeyboardAnimationDurationUserInfoKey] floatValue];
    
    [UIView animateWithDuration:duaration animations:^{
        self.view.frame = CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT);
    }];
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

-(void)viewWillAppear:(BOOL)animated
{
    [self.navigationController setNavigationBarHidden:NO];
}

-(void)viewDidLayoutSubviews
{
    [super viewDidLayoutSubviews];
    [phoneNuberTf setValue:[UIColor lightGrayColor] forKeyPath:@"_placeholderLabel.textColor"];
    [passWordTf setValue:[UIColor lightGrayColor] forKeyPath:@"_placeholderLabel.textColor"];
    [conformPassword setValue:[UIColor lightGrayColor] forKeyPath:@"_placeholderLabel.textColor"];
    [avtarTf setValue:[UIColor lightGrayColor] forKeyPath:@"_placeholderLabel.textColor"];
    
    
    mobileIv.layer.borderWidth = 1.0;
    mobileIv.layer.borderColor = UIColorHexRGBA(linBoardSepLineColor, 1.0).CGColor;
    viaCodeIv.layer.borderColor =UIColorHexRGBA(linBoardSepLineColor, 1.0).CGColor;
    viaCodeIv.layer.borderWidth = 1.0;
    
    setPwdIv.layer.borderColor =UIColorHexRGBA(linBoardSepLineColor, 1.0).CGColor;
    setPwdIv.layer.borderWidth = 1.0;
    
    confermIv.layer.borderColor =UIColorHexRGBA(linBoardSepLineColor, 1.0).CGColor;
    confermIv.layer.borderWidth = 1.0;
    
    
    getViaBtn.layer.borderColor =UIColorHexRGBA(linBoardSepLineColor, 1.0).CGColor;
    getViaBtn.layer.borderWidth = 1.0;
    
    registerBtn.layer.borderColor =UIColorHexRGBA(linBoardSepLineColor, 1.0).CGColor;
    registerBtn.layer.borderWidth = 1.0;
}

- (IBAction)haveAccountAction:(UIButton *)sender
{
    [self.navigationController popViewControllerAnimated:YES];
}



- (IBAction)getViaBtnAction:(UIButton *)sender
{
//    "mobile": "15033201853",
//    "password": "1",
//    "recommendPerson":"946490",
//    "userType":"1"
    
    
    MBProgressHUD *mbhud = [[MBProgressHUD alloc] initWithView:self.view];
    mbhud.mode = MBProgressHUDModeText;
    mbhud.tag = 102;
    [self.view addSubview:mbhud];
    
    [mbhud show:YES];
    phoneNuberTf.text = [phoneNuberTf.text stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]];
    if (phoneNuberTf.text.length == 0) {
        mbhud.labelText = @"请填写手机号";
        [self performSelector:@selector(dismissHud) withObject:nil afterDelay:1.5f];
        return;
    }
    
    BOOL isMobile = [self isPureNumandCharacters:phoneNuberTf.text];
    
    if (!isMobile||phoneNuberTf.text.length!=11) {
        mbhud.labelText = @"手机号不合法";
        [self performSelector:@selector(dismissHud) withObject:nil afterDelay:1.5f];
        return;
    }
    
    if ([[sender titleLabel].text isEqualToString:@"获取验证码"]) {
        //向服务端rest接口获取验证码
        //SitaShortMessageCer
        [self getSortMessageFromnet];
    }
    
    __block int timeout=120;//倒计时时间
    dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
    _timer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0,queue);
    dispatch_source_set_timer(_timer,dispatch_walltime(NULL, 0),1.0*NSEC_PER_SEC, 0); //每秒执行
    dispatch_source_set_event_handler(_timer, ^{
        if(timeout<=0){ //倒计时结束，关闭
            dispatch_source_cancel(_timer);
            dispatch_async(dispatch_get_main_queue(), ^{
                [sender setTitle:@"获取验证码" forState:UIControlStateNormal];
                sender.userInteractionEnabled = YES;
            });
        }else{
            sender.userInteractionEnabled = NO;
            int seconds = timeout % 120;
            dispatch_async(dispatch_get_main_queue(), ^{
                NSString *tittleString = [NSString stringWithFormat:@"%d秒",seconds];
                if ([tittleString isEqualToString:@"0秒"]) {
                    //更新ui
                    [sender setTitle:@"120秒" forState:UIControlStateNormal];
                }else{
                    //更新ui
                    [sender setTitle:tittleString forState:UIControlStateNormal];
                }
                
            });
            timeout--;
        }
    });
    dispatch_resume(_timer);

    
}
    
    


- (BOOL)isPureNumandCharacters:(NSString *)string
{
    string = [string stringByTrimmingCharactersInSet:[NSCharacterSet decimalDigitCharacterSet]];
    if(string.length > 0)
    {
        return NO;
    }
    return YES;
}



-(void)getSortMessageFromnet
{
    
    MBProgressHUD *hud = [self.view viewWithTag:102];
    hud.labelText = @"获取验证码";
    
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    [manager.requestSerializer setTimeoutInterval:10.0f];
    manager.requestSerializer = [AFJSONRequestSerializer serializer];
    
    NSString *mUrl = [NSString stringWithFormat:@"%@%@%@%@",linboardBaseUrl,linboardGetViaCode,phoneNuberTf.text,@"?type=1"];
    //NSLog(@"****:%@",mUrl);
    [manager GET:mUrl parameters:nil progress:^(NSProgress * _Nonnull downloadProgress) {
        ;
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
          NSDictionary *infdic = [responseObject valueForKey:@"data"] ;
        //NSLog(@"%@",infdic);
        [hud removeFromSuperview];
        ;
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        hud.labelText = @"获取验证码失败!";
        [self performSelector:@selector(dismissHud) withObject:nil afterDelay:1.5f];
    }];
    

    
    
}

- (IBAction)registerAction:(UIButton *)sender
{
    [avtarTf resignFirstResponder];
    [passWordTf resignFirstResponder];
    [phoneNuberTf resignFirstResponder];
    [conformPassword resignFirstResponder];
    
    
    MBProgressHUD *hud = [[MBProgressHUD alloc] initWithView:self.view];
    hud.labelText = @"注册中......";
    hud.tag = 102;
    hud.mode =MBProgressHUDModeText;
    [self.view addSubview:hud];
    [hud show:YES];
    
    
    //手机号数字,位数验证,两次密码一致验证
    phoneNuberTf.text = [phoneNuberTf.text stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]];
    
    passWordTf.text = [passWordTf.text stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]];
    
    conformPassword.text = [conformPassword.text stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]];
    
      avtarTf.text = [conformPassword.text stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]];
    
    
    if (phoneNuberTf.text.length == 0||passWordTf.text.length == 0||conformPassword.text.length == 0|| avtarTf.text==0)
    {
        hud.labelText = @"注册信息有误!";
        [self performSelector:@selector(dismissHud) withObject:nil afterDelay:2.0f];
        return;
    }else{
        //检查是否是合法的手机号
        BOOL isMobile = [self isPureNumandCharacters:phoneNuberTf.text];
        
        if (!isMobile||phoneNuberTf.text.length!=11) {
            hud.labelText = @"请输入正确的手机号!";
            [self performSelector:@selector(dismissHud) withObject:nil afterDelay:2.0f];
            return;
        }
        
        if (![passWordTf.text isEqualToString:conformPassword.text]) {
            hud.labelText = @"两次输入的密码不一致!";
            [self performSelector:@selector(dismissHud) withObject:nil afterDelay:2.0f];
            return;
        }
    }
    
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    [manager.requestSerializer setTimeoutInterval:10.0f];
    manager.requestSerializer = [AFJSONRequestSerializer serializer];
    NSString *mUrl = [NSString stringWithFormat:@"%@%@",linboardBaseUrl,linboardRegister];
    NSDictionary *parametersDic = [NSDictionary dictionaryWithObjectsAndKeys:phoneNuberTf.text,@"mobile",passWordTf.text,@"password",avtarTf.text,@"recommendPerson",@"1",@"userType",nil];
    
    [manager POST:mUrl parameters:parametersDic progress:^(NSProgress * _Nonnull uploadProgress) {
        ;
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        NSString *errorcode = [responseObject valueForKey:@"errorCode"];
        if ([errorcode isEqualToString:@"0"]) {
            NSDictionary *infdic = [responseObject valueForKey:@"data"];
           // NSLog(@"*****:%@",infdic);
            ResisterObj *bettryInfo = [ResisterObj mj_objectWithKeyValues:infdic];

            [[NSUserDefaults standardUserDefaults] setValue:bettryInfo.accountId forKey:@"pallaAccountId"];
            [[NSUserDefaults standardUserDefaults] synchronize];
            
            [[NSUserDefaults standardUserDefaults] setValue:bettryInfo.avatar forKey:@"pallaAvatar"];
            [[NSUserDefaults standardUserDefaults] synchronize];
            
            [[NSUserDefaults standardUserDefaults] setValue:[NSString stringWithFormat:@"%d",bettryInfo.gender] forKey:@"pallaGender"];
            [[NSUserDefaults standardUserDefaults] synchronize];
            
            [[NSUserDefaults standardUserDefaults] setValue:bettryInfo.mobile forKey:@"pallaMobile"];
            [[NSUserDefaults standardUserDefaults] synchronize];
            
            [[NSUserDefaults standardUserDefaults] setValue:bettryInfo.imPassword forKey:@"pallaImPassword"];
            [[NSUserDefaults standardUserDefaults] synchronize];
            
            [[NSUserDefaults standardUserDefaults] setValue:bettryInfo.nickName forKey:@"pallaNickName"];
            [[NSUserDefaults standardUserDefaults] synchronize];
            
            [[NSNotificationCenter defaultCenter] postNotificationName:@"registerSuccessNoty" object:bettryInfo];
            [self.navigationController popViewControllerAnimated:YES];
        }
        [hud removeFromSuperview];
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        //NSLog(@"%@",error);
        
        NSData *dicdata=[[error userInfo] valueForKey:@"com.alamofire.serialization.response.error.data"];
        NSDictionary *dic=[NSJSONSerialization JSONObjectWithData:dicdata options:NSJSONReadingMutableContainers error:nil];
        //NSLog(@"****:%@",dic);
        if (dic.count == 2) {
            NSString *infoString = [dic valueForKey:@"data"];
            if ([infoString isEqualToString:@"MOBILE_EXIST"]) {
                hud.labelText = @"该手机号已被注册!";
            }else{
                hud.labelText = @"注册失败了!";
            }
            //hud.labelText = @"用户名或密码错误!";
        }else{
            hud.labelText = @"注册失败了!";
        }
        //hud.labelText = @"注册失败!";
        [self performSelector:@selector(dismissHud) withObject:nil afterDelay:1.5f];
        ;
    }];
}

//删除hud102
-(void)dismissHud
{
    MBProgressHUD *mbhud = [self.view viewWithTag:102];
    if (mbhud) {
        [mbhud removeFromSuperview];
    }
}

@end
